﻿using DataAchive.Helper;
using DataAchive.Model;
using DataAchive.Model.DBModels;
using DataAchive.Model.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using static DataAchive.Model.ViewModels.InfoViewModel;

namespace DataAchive
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class InfoWindow : Window
    {
        private List<AChiveNG> ngList = new List<AChiveNG>();
        private NgData ngData;
        private List<FilterModel> filterModel;
        private DataGridHelper gridHelper = new DataGridHelper();
        private AChiveInfo queryData = new AChiveInfo();
        private static Dictionary<string, int> FaultCode = new Dictionary<string, int>();
        public InfoWindow(object[] param)
        {
            try
            {
                GetFaultCode();
                SoftCommon.Log.Write($"InfoWindow open!");
                if (param != null)
                {
                    ngData = param[0] as NgData;
                    if (ngData != null)
                    {
                        queryData.NG_Id = ngData.ID;
                    }
                    if (param.Count() >= 2)
                        queryData = param[1] as AChiveInfo;
                    if (param.Count() >= 3)
                        filterModel = param[2] as List<FilterModel>;

                }
                InitializeComponent();
                InitializeImageParams();
              //  SoftCommon.Log.Write($"界面初始化，获取图片数据");
               // InfoViewModel infoViewModel = new InfoViewModel();
                gridHelper.DataGridBuilder(typeof(InfoViewModel.InfoData), viewData);
             //   SoftCommon.Log.Write($"表格生成");
               // this.DataContext = infoViewModel;
             //   SoftCommon.Log.Write($"视图模型赋值");
                BingData(queryData, filterModel);
              //  SoftCommon.Log.Write($"数据绑定");
             
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, "页面初始化失败：" + ex.Message);
            }

        }


        public void BingData(AChiveInfo queryEntity, List<FilterModel> filterModel)
        {
            try
            {
                M_QueryBuilder queryBuilder = new M_QueryBuilder();
                List<AChiveInfo> list = queryBuilder.GetModelList(queryEntity, filterModel);
                var ngIdList = list.GroupBy(g => g.NG_Id).Select(s => (object)s.Key).ToArray();
                ngList = queryBuilder.GetModelList<AChiveNG>(new AChiveNG(), new List<FilterModel>() { new FilterModel() { Name = "id", Type = FilterType.In, In = ngIdList } });
                SoftCommon.Log.Write($"BingData:");
                List<InfoViewModel.InfoData> resultData = new List<InfoViewModel.InfoData>();
                foreach (AChiveInfo item in list)
                {
                    AChiveNG ngModel = ngList.Find(w => w.ID == item.NG_Id);
                    InfoViewModel.InfoData model = new InfoViewModel.InfoData();
                    model.ID = Convert.ToInt32(item.ID ?? 0);
                    model.Lot_Id = ngModel?.Lot_Id;
                    model.Classify = item.Classify;
                    model.PX = item.PX;
                    model.PY = item.PY;
                    model.Width = item.Width;
                    model.Height = item.Height;
                    model.Creator = item.Creator;
                    model.NG_Id = FaultCode.ContainsKey(item.Classify)? FaultCode[item.Classify]:-1;
                    model.Cell_Location = GetLocation(new System.Drawing.Point(Convert.ToInt32(item.PX), Convert.ToInt32(item.PY)));
                    resultData.Add(model);
                }
                SoftCommon.Log.Write($"处理数据，转换视图实体");
                //InfoViewModel infoViewModel = this.DataContext as InfoViewModel;
                InfoViewModel infoViewModel = new InfoViewModel();
                infoViewModel.InfoAllDataList = new ObservableCollection<InfoViewModel.InfoData>(resultData);
                infoViewModel.InfoQuery = new InfoViewModel.InfoData();
                GetPageList(infoViewModel);
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, "BingData error：" + ex.Message);
            }

        }

        //获取异常故障码
        private static void GetFaultCode()
        {
            if (FaultCode.Count > 0)
            {
                return;
            }
            FaultCode.Clear();
            XmlNode settingClassIfyPriority = Setting.GetXmlNode("setting/ClassIfyNgCode");
            if (settingClassIfyPriority != null)
            {
                for (int i = 0; i < settingClassIfyPriority.ChildNodes.Count; i++)
                {
                    var faultVal = settingClassIfyPriority.ChildNodes[i].InnerText;
                    if (faultVal != null)
                    {
                        var codeAndFault = faultVal.Split(':');
                        FaultCode.Add(codeAndFault[1],Convert.ToInt32(codeAndFault[0]) );
                    }
                }

            }
        }

        private void Select_Click(object sender, RoutedEventArgs e)
        {
            SoftCommon.Log.Write($"查询按钮点击");
            InfoViewModel infoViewModel = this.DataContext as InfoViewModel;
            //AChiveInfo queryEntity = new AChiveInfo();
            //queryEntity.NG_Id = ngData.ID;
            //queryEntity.Equipment_Id = infoViewModel.InfoQuery.Equipment_Id;
            BingData(queryData, filterModel);
        }

        private void Exprot_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SoftCommon.Log.Write($"导出按钮点击");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                //$@"{path}\";
                if (string.IsNullOrWhiteSpace(path))
                {
                    return;
                }
                string fileName = FileHelper.GetFileName(path, $@"Info-{ngData.Lot_Id}.xlsx");
                InfoViewModel infoViewModel = this.DataContext as InfoViewModel;
                //List<InfoExportViewModel> dataList = infoViewModel.InfoDataList.Select(s => new InfoExportViewModel()
                //{
                //    ID = Convert.ToInt32(s.ID),
                //    Lot_Id = ngData.Lot_Id,
                //    Classify = s.Classify,
                //    PX = s.PX,
                //    PY = s.PY,
                //    Width = s.Width,
                //    Height = s.Height,
                //    Creator = s.Creator,
                //    Cell_Location = s.Cell_Location
                //}).ToList();


                var allData = this.DataContext as InfoViewModel;
                List<string> checkedColumns = allData.ItemsData.Where(s => s.IsCheck).Select(s => s.ViewName).ToList();
                ExcelHelper.ExportColumn(fileName, infoViewModel.InfoAllDataList.ToList(), checkedColumns, "详细信息");
                SoftCommon.Log.Write($"导出文件保存成功！");
                FileHelper folderHelper = new FileHelper();
                folderHelper.OpenFolder(path);
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, "导出异常：" + ex.Message);
            }

        }

        private void SetColumn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SoftCommon.Log.Write($"列筛选按钮点击");
                var allData = this.DataContext as InfoViewModel;
                List<string> checkedColumns = allData.ItemsData.Where(s => s.IsCheck).Select(s => s.ViewName).ToList();

                // 清除已有的列
                viewData.Columns.Clear();
                SoftCommon.Log.Write($"清除页面Table信息");
                gridHelper.DataGridBuilder(typeof(InfoViewModel.InfoData),  viewData, checkedColumns);
                SoftCommon.Log.Write($"重新根据列头创建表格");
                BingData(queryData, filterModel);
                SoftCommon.Log.Write($"数据绑定");
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, "列头筛选异常：" + ex.Message);
            }

        }

        //char[] LettersBit =new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        //char[] NumsBit=new char[] { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
        public double ImageWidth = 0;
        public double ImageHeight = 0;
        double[] ImageMargins = new double[] { 0, 0, 0, 0, 0 };
        string[] xBit;
        string[] yBit;
        public string GetLocation(System.Drawing.Point coordinate)
        {
            try
            {
              //  SoftCommon.Log.Write($"位置信息处理");
                string result = "";
                if (ImageWidth > 0 || ImageHeight > 0)
                {
                    //double LeftRightMargin = Convert.ToDouble(ngData.Left_Right_Margin);
                    //double TopBottomMargin = Convert.ToDouble(ngData.Top_Bottom_Margin);
                    // 计算所在的小矩形块索引
                    int x = (int)Math.Floor((double)(coordinate.X) / (ImageWidth / Convert.ToInt32(ngData.Row_Number)));
                    int y = (int)Math.Floor((double)(coordinate.Y) / (ImageHeight / Convert.ToInt32(ngData.Column_Number)));
                    result = $"{xBit[x]}*{yBit[y]}";
                }
                return result;
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, "GetLocation异常：" + ex.Message);
                return "";
            }

        }


        /// <summary>
        /// 初始化获取图片信息
        /// </summary>
        public void InitializeImageParams()

        {
            try
            {

                if (ngData != null)
                {
                    SoftCommon.Log.Write($"初始化根据主表获取图片信息");
                    //获取图片
                    string imagePath = Setting.GetXmlNode("setting/ImageCompass/ImageSourcePath").InnerText;
                    SoftCommon.Log.Write($"获取配置地址：{imagePath}");
                    string pattern = @"(yyyy|yy|MM|dd|YYYY|YY|DD)";



                    // 使用正则表达式匹配字符串
                    MatchCollection sourcePathMatches = Regex.Matches(imagePath, pattern);
                    if (sourcePathMatches != null && sourcePathMatches.Count > 0)
                    {
                        string sourceReplace = imagePath.Substring(sourcePathMatches[0].Index, 10);
                        string sourceFormat = sourceReplace.Replace("YYYY", "yyyy").Replace("DD", "dd");
                        imagePath = imagePath.Replace(sourceReplace, DateTime.Now.Date.ToString(sourceFormat));
                    }

                    //判断文件件是否存在
                    if (!Directory.Exists(imagePath))
                        Directory.CreateDirectory(imagePath);


                    // 查找匹配文件名的所有文件
                    SoftCommon.Log.Write($"查找文件{ngData.Lot_Id}_M");
                    // 获取文件夹中的所有图像文件
                    //string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff" };
                    //string[] files = FileHelper.ListAllFilesWithFilter($"{imagePath}", imageExtensions);
                    string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff" };
                    string[] files = FileHelper.ListAllImageFiles(imagePath, imageExtensions, ngData.Lot_Id + "_M");

                    if (files != null && files.Any())
                    {
                        SoftCommon.Log.Write($"找到{files.Length}个同名文件！");
                        foreach (string file in files)
                        {
                            // 检查文件是否为图片文件（可以根据文件内容进行判断）
                            if (IsImageFile(file))
                            {
                                SoftCommon.Log.Write($"查找到图片：{file}");
                                imagePath = file;
                                break;
                            }
                        }
                    }
                    else
                    {
                        SoftCommon.Log.Write($"未找到同名文件！");
                    }


                    if (!string.IsNullOrEmpty(imagePath) && File.Exists(imagePath))
                    {
                        SoftCommon.Log.Write($"读取图片，获取图片信息");
                        using (System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath))
                        {
                            // 获取图片尺寸
                            ImageWidth = image.Width;
                            ImageHeight = image.Height;
                        }
                    }

                    //边距
                    double[] ImageMargins = new double[] {
                        Convert.ToDouble(ngData.Left_Right_Margin),
                        Convert.ToDouble(ngData.Left_Right_Margin),
                        Convert.ToDouble(ngData.Top_Bottom_Margin),
                        Convert.ToDouble(ngData.Top_Bottom_Margin),
                        10};
                    //字符类型 0数字 1字母 
                    if (ngData.Row_Type == "0")
                        xBit = Enumerable.Range(1, Convert.ToInt32(ngData.Row_Number)).Select(x => x.ToString()).ToArray();
                    else
                        xBit = Enumerable.Range('A', Convert.ToInt32(ngData.Row_Number)).Select(x => ((char)x).ToString()).ToArray();


                    if (ngData.Column_Type == "0")
                        yBit = Enumerable.Range(1, Convert.ToInt32(ngData.Column_Number)).Select(x => x.ToString()).ToArray();
                    else
                        yBit = Enumerable.Range('A', Convert.ToInt32(ngData.Column_Number)).Select(x => ((char)x).ToString()).ToArray();


                    //排序
                    if (!Convert.ToBoolean(Convert.ToInt32(ngData.Row_Order)))
                        xBit = xBit.Skip(0).Take(Convert.ToInt32(ngData.Row_Number)).Reverse().ToArray();

                    if (!Convert.ToBoolean(Convert.ToInt32(ngData.Column_Order)))
                        yBit = yBit.Skip(0).Take(Convert.ToInt32(ngData.Column_Number)).Reverse().ToArray();

                    SoftCommon.Log.Write($"根据主数据信息设定位置生成规则");
                }
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, "初始化图片信息异常：" + ex.Message);
            }
        }
        static bool IsImageFile(string filePath)
        {
            // 这里可以根据文件内容或其他特征来判断是不是图片文件
            // 这里简单地根据文件扩展名来判断
            string extension = Path.GetExtension(filePath).ToLower();
            return extension == ".jpg" || extension == ".jpeg" || extension == ".png" ||
                   extension == ".bmp" || extension == ".gif" || extension == ".tiff";
        }

        private void ComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var data = DataContext as InfoViewModel;
            if (data == null) data = new InfoViewModel();
            ComboBox comboBox = sender as ComboBox;
            if (comboBox.SelectedItem != null)
            {
                ComboBoxItem selectedItem = (ComboBoxItem)comboBox.SelectedItem;
                int selectedTag = Convert.ToInt32(selectedItem.Tag);
                data.InfoDataList.PageIndex = 1;
                data.InfoDataList.PageSize = selectedTag;
                GetPageList(data);
            }
        }

        private void Pagination_CurrentIndexChanged(object sender, Panuon.UI.Silver.Core.CurrentIndexChangedEventArgs e)
        {
            var data = DataContext as InfoViewModel;
            GetPageList(data);
        }

        private void GetPageList(InfoViewModel infoViewModel)
        {
            if (infoViewModel == null) infoViewModel = new InfoViewModel();
            if (infoViewModel.InfoDataList == null)
                infoViewModel.InfoDataList = new Page<ObservableCollection<InfoViewModel.InfoData>>();
            infoViewModel.InfoDataList.Count = infoViewModel.InfoAllDataList.Count();
            int pageAdd = 0;
            if (infoViewModel.InfoDataList.Count % (infoViewModel.InfoDataList.PageSize == 0 ? 10 : infoViewModel.InfoDataList.PageSize) != 0)
                pageAdd += 1;
            infoViewModel.InfoDataList.PageCount = infoViewModel.InfoDataList.Count / (infoViewModel.InfoDataList.PageSize == 0 ? 10 : infoViewModel.InfoDataList.PageSize) + pageAdd;

            //数据
            var pageData = infoViewModel.InfoAllDataList
                .Skip((infoViewModel.InfoDataList.PageIndex - 1) * infoViewModel.InfoDataList.PageSize)
                .Take(infoViewModel.InfoDataList.PageSize);
            if (infoViewModel.InfoDataList.Data == null || !infoViewModel.InfoDataList.Data.Any())
                infoViewModel.InfoDataList.Data = new ObservableCollection<InfoData>();
            infoViewModel.InfoDataList.Data.Clear();
            foreach (var item in pageData)
            {
                infoViewModel.InfoDataList.Data.Add(item);
            }
            DataContext = infoViewModel;
        }
    }
}
